package com.chuangke.flow.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangke.admin.data.builder.UserDataBuilder;
import com.chuangke.metadata.service.SysBillSerialService;
import com.chuangke.common.data.builder.DataBuildConfig;
import com.chuangke.common.data.builder.DataBuilder;
import com.chuangke.flow.constant.FlowConstant;
import com.chuangke.flow.dao.mapper.FlowBasicMapper;
import com.chuangke.flow.domain.OrderModel;
import com.chuangke.flow.entity.FlowBasic;
import com.chuangke.flow.service.FlowBasicService;
import com.chuangke.flow.service.FlowInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * implService业务层处理
 * 
 * @author chuangke
 * @date "2020-12-29"
 */
@Service
public class FlowBasicServiceImpl extends ServiceImpl<FlowBasicMapper, FlowBasic> implements FlowBasicService {

	@Autowired
	private FlowBasicMapper flowBasicMapper;
	@Autowired
	private SysBillSerialService orderIdWorker;
	@Autowired
	private FlowInstanceService flowInstanceService;

    /**
     * 查询impl列表
     * 
     * @param flowBasic impl
     * @return impl
     */
    @Override
    public List<FlowBasic> selectFlowBasicList(FlowBasic flowBasic){
	    List<FlowBasic> resultList=flowBasicMapper.selectList(new QueryWrapper<>());
	    DataBuilder.of(resultList)
			.appendBuilder(new UserDataBuilder(), new DataBuildConfig("createdBy", "createdBy"),
					new DataBuildConfig("updatedBy", "updatedBy")).build();
	        return resultList;
    }

    /**
     * 新增impl
     * 
     * @param flowBasic impl
     * @return 结果
     */
    @Override
	@Transactional(rollbackFor = Exception.class)
     public String saveOrUpdateFlowBasic(FlowBasic flowBasic){
    	String orderId=flowBasic.getId();
		if (StrUtil.isBlank(orderId)) {
			orderId=saveOrder(flowBasic);
		} else {
			updateOrder(flowBasic);
		}
		return orderId;
    }

    @Transactional(rollbackFor = Exception.class)
	@Override
	public String saveOrder(FlowBasic flowBasic) {
		String orderId = orderIdWorker.nextSerial(FlowConstant.ORDER_NO);
		flowBasicMapper.insert(flowBasic);
		startProcessInstance(flowBasic);
		return orderId;
	}
    
    private void startProcessInstance(FlowBasic flowBasic) {
		Map<String, Object> values = new HashMap<>();//values用来存放表单中流程用到的属性，例如表单中根据金额判断走向，需要传入金额字段
		values.put("amount", flowBasic.getAmount()) ;
		OrderModel orderModel = new OrderModel() ;
		orderModel.setOrderId(flowBasic.getId());
		orderModel.setOrderType(flowBasic.getType());
		orderModel.setOrderDeptId(flowBasic.getDeptId());
		orderModel.setOrderDate(flowBasic.getDate());
		orderModel.setOrderProjectId(flowBasic.getProjectId());
		orderModel.setOrderAmount(flowBasic.getAmount());
		orderModel.setOrderRemarks(flowBasic.getRemarks());
		orderModel.setOrderCreatedBy(flowBasic.getCreatedBy());
		orderModel.setOrderCreatedAt(flowBasic.getCreatedAt());
		orderModel.setOrderService(FlowBasicService.class.getName());
		orderModel.setVariables(values);
		flowInstanceService.startInstanceByFlowId(flowBasic.getFlowId(), Arrays.asList(orderModel)) ;
	}
    
    @Transactional(rollbackFor = Exception.class)
	@Override
	public void updateOrder(FlowBasic flowBasic) {
    	deleteFlowBasicByIds(Collections.singletonList(flowBasic.getId()));
    	flowBasicMapper.insert(flowBasic);
	}
    /**
     * 批量删除impl
     * 
     * @param ids 需要删除的implID
     * @return 结果
     */
    @Override
    public int deleteFlowBasicByIds(List<String> ids){
    	return flowBasicMapper.deleteBatchIds(ids);
    }

	@Override
	public void submit(String id, Map<String, Object> variables) {
		flowBasicMapper.update(new FlowBasic(),
                Wrappers.<FlowBasic>lambdaUpdate().set(FlowBasic::getStatus, FlowConstant.STATUS_SPZ).eq(FlowBasic::getId, id));
	}

	@Override
	public void reject(String id, Map<String, Object> variables) {
		flowBasicMapper.update(new FlowBasic(),
                Wrappers.<FlowBasic>lambdaUpdate().set(FlowBasic::getStatus, FlowConstant.STATUS_BZZ).eq(FlowBasic::getId, id));
	}

	@Override
	public void complete(String id, Map<String, Object> variables) {
		flowBasicMapper.update(new FlowBasic(),
                Wrappers.<FlowBasic>lambdaUpdate().set(FlowBasic::getStatus, FlowConstant.STATUS_YWC).eq(FlowBasic::getId, id));
	}

}